const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const ResponseHelper = require("../ResponseHelper");
// const os = require("os");
const fileUrl = require("../../tools/fileUrl");

const allowedMimetype = [
  "image/jpeg",
  "jpg",
  "jpeg",
  "image/png",
  "image/bmp",
  "gif",
  "video/x-matroska",
];

function fileFilter(req, file, cb) {
  // 这个函数应该调用 `cb` 用boolean值来指示是否应接受该文件
  if (allowedMimetype.includes(file.mimetype)) {
    //接受这个文件，使用`true`，像这样:
    cb(null, true);
  } else {
    // 拒绝这个文件，使用`false`，像这样:
    cb(new Error("Reject this type of picture"));
  }
  // 如果有问题，你可以总是这样发送一个错误:
  //cb(new Error('I don\'t have a clue!'))
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    let uploadPath = `${fileUrl.uploadStaticPath}`
    // let uploadPath = "C:\\ownnodeuploads";
    // const system = os.platform();
    // if (system === "linux") {
    //   uploadPath = "/home/cobot/ownnodeuploads";
    // }
    console.log("uploadPath", uploadPath);
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    const fileName = Math.random().toString(36).slice(-8);
    const timeSamp = Date.now();
    let ext = path.extname(file.originalname);
    console.log("================", file);
    if (file.originalname === "blob" && file.mimetype != "image/bmp") {
      if (file.mimetype == "image/png") {
        ext = ".png";
      } else {
        ext = ".mp4";
      }
    } else if (file.originalname === "blob" && file.mimetype == "image/bmp") {
      ext = ".bmp";
    } else if (!ext && file.mimetype == "image/png") {
      ext = ".png";
    }
    cb(null, `${fileName}_${timeSamp}${ext}`);
  },
});

const upload = multer({
  storage: storage,
  limits: { fileSize: 1024 * 1024 * 10 },
  fileFilter,
});

router.post("/", upload.single("file"), (req, res, next) => {
  ResponseHelper.sendData(
    `http://${req.headers.host}/pubilc/uploads/${req.file.filename}`,
    res
  );
});

module.exports = router;
